import React, { useEffect, useState } from "react";
import Page from "./Page";
import UpdatePassword from "./UpdatePwd";

import Register from "./Register";

import "./index.css";

import Login from "./Login";

import { useParams } from "react-router-dom";

function UserApp() {
  const [step, setStep] = useState("login"); // 步骤
  const [username, setUsername] = useState(""); // 用户名
  const [password, setPassword] = useState(""); // 密码
  const [userInfo, setUserInfo] = useState({
    username: "",
  });

  const { step: routeStep } = useParams(); // 获取路由参数

  useEffect(() => {
    if (routeStep) {
      setStep(routeStep);
    }
  }, [routeStep]);

  const loginStep = (msg, username, password) => {
    username && setUsername(username);
    password && setPassword(password);

    if (msg) {
      console.log("msg:", msg.data);
      const res = msg.data;
      if (res?.response?.message) {
        message.error(res?.response?.message);
      }
      if (res.next_types) {
        // 下一步操作
        if (res.next_types[0] == "login") setStep("login");
        if (res.next_types[0] == "change_password") setStep("updatePwd");
        if (res.next_types[0] == "totp") setStep("totp");
        if (res.next_types[0] === "verify_code_email") setStep("email");
        if (res.next_types[0] === "verify_code_sms") setStep("message");
      }
    } else {
    }
  };

  // 登录成功回调函数
  function callback() {
    const cb =
      new URLSearchParams(window.location.search).get("callback") || "";
    let href = "/";
    try {
      href = window.atob(cb) || "/";
    } catch {}
    window.location.href = href;
  }

  return (
    <>
      <Page>
        {step === "login" && <Login onStep={loginStep}></Login>}
        {step == "updatePwd" && (
          <UpdatePassword
            username={username}
            onStep={loginStep}
            password={password}
          />
        )}
        {step === "register" && (
          <Register userInfo={userInfo} callback={callback} />
        )}
      </Page>
    </>
  );
}

export default UserApp;
